<template>
  <div class="settings-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Setting /></el-icon>
            <span class="header-title">系统设置</span>
          </div>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 系统信息 -->
        <el-tab-pane label="系统信息" name="info">
          <div class="tab-content">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="系统名称">员工事务管理系统</el-descriptions-item>
              <el-descriptions-item label="系统版本">v1.0.0</el-descriptions-item>
              <el-descriptions-item label="当前用户">{{ userInfo.name || userInfo.username }}</el-descriptions-item>
              <el-descriptions-item label="用户角色">{{ getRoleName(userInfo.role) }}</el-descriptions-item>
              <el-descriptions-item label="登录时间">{{ loginTime }}</el-descriptions-item>
              <el-descriptions-item label="系统状态">
                <el-tag type="success">运行中</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>
        
        <!-- 数据统计 -->
        <el-tab-pane label="数据统计" name="statistics">
          <div class="tab-content">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-card class="stat-card" shadow="hover">
                  <div class="stat-item">
                    <div class="stat-value">{{ statistics.totalUsers }}</div>
                    <div class="stat-label">用户总数</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card" shadow="hover">
                  <div class="stat-item">
                    <div class="stat-value">{{ statistics.totalAttendance }}</div>
                    <div class="stat-label">考勤记录</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card" shadow="hover">
                  <div class="stat-item">
                    <div class="stat-value">{{ statistics.totalSalary }}</div>
                    <div class="stat-label">薪资记录</div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card class="stat-card" shadow="hover">
                  <div class="stat-item">
                    <div class="stat-value">{{ statistics.totalLeave }}</div>
                    <div class="stat-label">请假记录</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        
        <!-- 系统配置 -->
        <el-tab-pane label="系统配置" name="config">
          <div class="tab-content">
            <el-form :model="configForm" label-width="150px" style="max-width: 600px">
              <el-form-item label="工作日设置">
                <el-input-number
                  v-model="configForm.workDays"
                  :min="1"
                  :max="31"
                  placeholder="每月工作日数"
                />
                <span style="margin-left: 10px; color: #909399;">天/月</span>
              </el-form-item>
              <el-form-item label="考勤提醒">
                <el-switch v-model="configForm.attendanceReminder" />
                <span style="margin-left: 10px; color: #909399;">开启后将在打卡时间提醒</span>
              </el-form-item>
              <el-form-item label="薪资提醒">
                <el-switch v-model="configForm.salaryReminder" />
                <span style="margin-left: 10px; color: #909399;">开启后将在发薪日提醒</span>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSaveConfig" :loading="saveLoading">
                  保存配置
                </el-button>
                <el-button @click="handleResetConfig">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <!-- 考勤规则设置 -->
        <el-tab-pane label="考勤规则" name="attendance">
          <div class="tab-content">
            <el-form :model="attendanceRuleForm" :rules="attendanceRuleRules" ref="attendanceRuleFormRef" label-width="180px" style="max-width: 700px">
              <el-form-item label="规则名称" prop="ruleName">
                <el-input
                  v-model="attendanceRuleForm.ruleName"
                  placeholder="请输入规则名称"
                  style="max-width: 300px"
                />
              </el-form-item>
              <el-form-item label="早上上班时间" prop="workStartTime">
                <el-time-picker
                  v-model="attendanceRuleForm.workStartTime"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  placeholder="选择早上上班时间"
                  style="max-width: 300px"
                />
                <span style="margin-left: 10px; color: #909399;">例如：09:00:00</span>
              </el-form-item>
              <el-form-item label="午休开始时间" prop="lunchStartTime">
                <el-time-picker
                  v-model="attendanceRuleForm.lunchStartTime"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  placeholder="选择午休开始时间"
                  style="max-width: 300px"
                />
                <span style="margin-left: 10px; color: #909399;">例如：12:00:00</span>
              </el-form-item>
              <el-form-item label="午休结束时间" prop="lunchEndTime">
                <el-time-picker
                  v-model="attendanceRuleForm.lunchEndTime"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  placeholder="选择午休结束时间（下午上班时间）"
                  style="max-width: 300px"
                />
                <span style="margin-left: 10px; color: #909399;">例如：13:30:00</span>
              </el-form-item>
              <el-form-item label="下班时间" prop="workEndTime">
                <el-time-picker
                  v-model="attendanceRuleForm.workEndTime"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  placeholder="选择下班时间"
                  style="max-width: 300px"
                />
                <span style="margin-left: 10px; color: #909399;">例如：18:00:00</span>
              </el-form-item>
              <el-form-item label="迟到阈值（分钟）" prop="lateThreshold">
                <el-input-number
                  v-model="attendanceRuleForm.lateThreshold"
                  :min="0"
                  :max="120"
                  placeholder="超过此时间算迟到"
                  style="max-width: 300px"
                />
                <span style="margin-left: 10px; color: #909399;">分钟</span>
              </el-form-item>
              <el-form-item label="早退阈值（分钟）" prop="earlyLeaveThreshold">
                <el-input-number
                  v-model="attendanceRuleForm.earlyLeaveThreshold"
                  :min="0"
                  :max="120"
                  placeholder="提前此时间算早退"
                  style="max-width: 300px"
                />
                <span style="margin-left: 10px; color: #909399;">分钟</span>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSaveAttendanceRule" :loading="attendanceRuleLoading">
                  保存考勤规则
                </el-button>
                <el-button @click="handleResetAttendanceRule">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <!-- 关于 -->
        <el-tab-pane label="关于" name="about">
          <div class="tab-content">
            <div class="about-content">
              <div class="about-logo">
                <el-icon :size="64" color="#409eff"><Setting /></el-icon>
              </div>
              <h2>员工事务管理系统</h2>
              <p class="version">版本 v1.0.0</p>
              <p class="description">
                一个功能完善的员工事务管理系统，支持考勤管理、薪资管理、请假管理等核心功能。
              </p>
              <div class="about-info">
                <p>© 2024 员工事务管理系统</p>
                <p>技术支持：系统管理员</p>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import request from '../utils/request'

export default {
  name: 'Settings',
  components: {
    Setting
  },
  setup() {
    const activeTab = ref('info')
    const saveLoading = ref(false)
    const attendanceRuleLoading = ref(false)
    const attendanceRuleFormRef = ref(null)
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
    const loginTime = ref(new Date().toLocaleString('zh-CN'))
    
    const statistics = ref({
      totalUsers: 0,
      totalAttendance: 0,
      totalSalary: 0,
      totalLeave: 0
    })
    
    const configForm = ref({
      workDays: 22,
      attendanceReminder: true,
      salaryReminder: true
    })
    
    const attendanceRuleForm = ref({
      id: null,
      ruleName: '标准工作时间',
      workStartTime: '09:00:00',
      lunchStartTime: '12:00:00',
      lunchEndTime: '13:30:00',
      workEndTime: '18:00:00',
      lateThreshold: 15,
      earlyLeaveThreshold: 15,
      flexibleWork: false,
      status: 'ACTIVE'
    })
    
    const attendanceRuleRules = {
      ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
      workStartTime: [{ required: true, message: '请选择早上上班时间', trigger: 'change' }],
      lunchStartTime: [{ required: true, message: '请选择午休开始时间', trigger: 'change' }],
      lunchEndTime: [{ required: true, message: '请选择午休结束时间', trigger: 'change' }],
      workEndTime: [{ required: true, message: '请选择下班时间', trigger: 'change' }],
      lateThreshold: [{ required: true, message: '请输入迟到阈值', trigger: 'blur' }],
      earlyLeaveThreshold: [{ required: true, message: '请输入早退阈值', trigger: 'blur' }]
    }
    
    const getRoleName = (role) => {
      const roleMap = {
        'EMPLOYEE': '员工',
        'MANAGER': '经理',
        'HR': 'HR',
        'OTHER': '其他'
      }
      return roleMap[role] || '未知'
    }
    
    // 加载统计数据
    const loadStatistics = async () => {
      try {
        // 加载用户总数
        try {
          const userRes = await request.get('/user/list')
          if (userRes.code === 200 && userRes.data) {
            statistics.value.totalUsers = userRes.data.length
          }
        } catch (e) {
          // 忽略权限错误
        }
        
        // 加载考勤记录数（简化处理，实际应该调用统计接口）
        // 这里暂时不调用，避免权限问题
        
        // 加载薪资记录数
        try {
          const salaryRes = await request.get('/salary/all')
          if (salaryRes.code === 200 && salaryRes.data) {
            statistics.value.totalSalary = salaryRes.data.length
          }
        } catch (e) {
          // 忽略权限错误
        }
      } catch (error) {
        console.error('加载统计数据失败', error)
      }
    }
    
    // 保存配置
    const handleSaveConfig = async () => {
      try {
        saveLoading.value = true
        const res = await request.put('/user/config', {
          workDays: configForm.value.workDays,
          attendanceReminder: configForm.value.attendanceReminder,
          salaryReminder: configForm.value.salaryReminder
        })
        
        if (res.code === 200) {
          ElMessage.success('配置保存成功')
        } else {
          ElMessage.error(res.message || '保存配置失败')
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('保存配置失败')
        }
      } finally {
        saveLoading.value = false
      }
    }
    
    // 重置配置
    const handleResetConfig = () => {
      configForm.value = {
        workDays: 22,
        attendanceReminder: true,
        salaryReminder: true
      }
      ElMessage.info('配置已重置为默认值')
    }
    
    // 加载配置
    const loadConfig = async () => {
      try {
        const res = await request.get('/user/config')
        if (res.code === 200 && res.data) {
          configForm.value = {
            workDays: res.data.workDays || 22,
            attendanceReminder: res.data.attendanceReminder !== undefined ? res.data.attendanceReminder : true,
            salaryReminder: res.data.salaryReminder !== undefined ? res.data.salaryReminder : true
          }
        }
      } catch (error) {
        console.error('加载配置失败', error)
        // 如果接口失败，使用默认值
        configForm.value = {
          workDays: 22,
          attendanceReminder: true,
          salaryReminder: true
        }
      }
    }
    
    // 加载考勤规则
    const loadAttendanceRule = async () => {
      try {
        const res = await request.get('/attendance/rule')
        if (res.code === 200 && res.data && res.data.length > 0) {
          // 获取第一个激活的规则，如果没有则使用第一个
          let rule = res.data.find(r => r.status === 'ACTIVE') || res.data[0]
          if (rule) {
            attendanceRuleForm.value = {
              id: rule.id,
              ruleName: rule.ruleName || '标准工作时间',
              workStartTime: rule.workStartTime || '09:00:00',
              lunchStartTime: rule.lunchStartTime || '12:00:00',
              lunchEndTime: rule.lunchEndTime || '13:30:00',
              workEndTime: rule.workEndTime || '18:00:00',
              lateThreshold: rule.lateThreshold || 15,
              earlyLeaveThreshold: rule.earlyLeaveThreshold || 15,
              flexibleWork: rule.flexibleWork || false,
              status: rule.status || 'ACTIVE'
            }
          }
        }
      } catch (error) {
        console.error('加载考勤规则失败', error)
        // 如果接口失败，使用默认值
      }
    }
    
    // 保存考勤规则
    const handleSaveAttendanceRule = async () => {
      if (!attendanceRuleFormRef.value) return
      await attendanceRuleFormRef.value.validate(async (valid) => {
        if (valid) {
          attendanceRuleLoading.value = true
          try {
            const res = await request.post('/attendance/rule', attendanceRuleForm.value)
            if (res.code === 200) {
              ElMessage.success('考勤规则保存成功')
              await loadAttendanceRule()
            } else {
              ElMessage.error(res.message || '保存考勤规则失败')
            }
          } catch (error) {
            if (error.response && error.response.data && error.response.data.message) {
              ElMessage.error(error.response.data.message)
            } else {
              ElMessage.error('保存考勤规则失败')
            }
          } finally {
            attendanceRuleLoading.value = false
          }
        }
      })
    }
    
    // 重置考勤规则
    const handleResetAttendanceRule = () => {
      attendanceRuleForm.value = {
        id: null,
        ruleName: '标准工作时间',
        workStartTime: '09:00:00',
        lunchStartTime: '12:00:00',
        lunchEndTime: '13:30:00',
        workEndTime: '18:00:00',
        lateThreshold: 15,
        earlyLeaveThreshold: 15,
        flexibleWork: false,
        status: 'ACTIVE'
      }
      ElMessage.info('考勤规则已重置为默认值')
    }
    
    onMounted(async () => {
      await loadStatistics()
      await loadConfig()
      await loadAttendanceRule()
    })
    
    return {
      activeTab,
      userInfo,
      loginTime,
      statistics,
      configForm,
      saveLoading,
      attendanceRuleForm,
      attendanceRuleFormRef,
      attendanceRuleRules,
      attendanceRuleLoading,
      getRoleName,
      handleSaveConfig,
      handleResetConfig,
      handleSaveAttendanceRule,
      handleResetAttendanceRule
    }
  }
}
</script>

<style scoped>
.settings-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.tab-content {
  padding: 24px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
}

.stat-item {
  padding: 20px 0;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.about-content {
  text-align: center;
  padding: 40px 20px;
}

.about-logo {
  margin-bottom: 24px;
}

.about-content h2 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: #303133;
}

.version {
  color: #909399;
  font-size: 16px;
  margin: 0 0 24px 0;
}

.description {
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
  max-width: 500px;
  margin: 0 auto 32px;
}

.about-info {
  margin-top: 40px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.about-info p {
  margin: 8px 0;
  color: #909399;
  font-size: 12px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>

